# -*- coding: utf-8 -*-
from odoo import api, fields, models, tools


class QualityOrder(models.Model):
    _name = "quality.order"
    _inherit = ['mail.thread', 'ir.needaction_mixin']
    _description = 'Quality Order'

    # name = fields.Char(u'名称', required=True)
    name = fields.Char(
        string=u'质检单号', copy=False)
    qua_user = fields.Many2one('res.users', u'质检员',readonly=True, required=True,default=lambda self: self.env.uid)
    qc_id = fields.Many2one('quality.check', u'质检方案名称', required=True)
    qo_lines = fields.One2many('quality.order.line', 'qo_id', u'质检单行')
    product_id = fields.Many2one('product.product', u'产品名称', required=True)
    picking_id = fields.Many2one('stock.picking', u'库存单据号')
    lot_id = fields.Many2one('stock.production.lot',u'批次号',domain="[('product_id', '=', product_id)]")
    qty = fields.Float(u'合格数量')
    mrp_id = fields.Many2one('mrp.production',u'制造订单号')
    produce_time = fields.Datetime(u'生产时间', required=True)

    @api.model
    def create(self, vals):
        if vals.get('name', False) == False:
            vals['name'] = self.env['ir.sequence'].get('quality.order')
            # vals['qua_user'] = self.env.uid
            # print self.env['ir.sequence'].get('quality.order')
        return super(QualityOrder, self).create(vals)
    # @api.multi
    @api.onchange('qc_id')
    def _onchange_para(self):
        if self.qc_id:
            self._cr.execute(
                """SELECT qp.id,qm.up_value,qm.low_value,qm.standard_value,qm.sequence,qm.id FROM quality_check qc LEFT JOIN qc_mid qm ON qm.qc_id = qc.id
                    LEFT JOIN qc_para qp ON qp.id = qm.qp_id WHERE qc.id=%d order by qm.sequence""" %
                self.qc_id[0])
            sd = self._cr.fetchall()
            lines = []
            for i in sd:
                line_item = {
                    'qp_id': i[0],
                    # 'standard_value': i[1],
                    'up_value': i[1],
                    'low_value': i[2],
                    'standard_value': i[3],
                    'sequence': i[4],
                    'qm_id': i[5]
                }
                lines += [line_item]
            self.update({'qo_lines': lines})

    @api.onchange('product_id')
    def _onchange_product_id(self):
        if self.product_id.qc_id:
            self.qc_id=self.product_id.qc_id
            # self._cr.execute(
            #     """SELECT qp.id,qp.up_value,qp.low_value FROM quality_check qc LEFT JOIN qc_mid qm ON qm.qc_id = qc.id
            #         LEFT JOIN qc_para qp ON qp.id = qm.qp_id WHERE qc.id=%d """ %
            #     self.qc_id[0])
            # sd = self._cr.fetchall()
            # lines = []
            # for i in sd:
            #     line_item = {
            #         'qp_id': i[0],
            #         # 'standard_value': i[1],
            #         'up_value': i[1],
            #         'low_value': i[2]
            #     }
            #     lines += [line_item]
            # self.update({'qo_lines': lines})

    @api.onchange('lot_id')
    def _onchange_lot_id(self):
        # purchase_order = self.env['purchase.order'].search(['','=',self.lot_id])
        if self.lot_id:
            self._cr.execute(
                """SELECT sp.id FROM stock_pack_operation_lot spol
                    LEFT JOIN stock_pack_operation spo ON spol.operation_id=spo.id
                    LEFT JOIN stock_picking sp ON sp.id=spo.picking_id
                    LEFT JOIN stock_picking_type spt ON spt.id=sp.picking_type_id
                    WHERE spt.code='incoming' AND spt.enable_return='true' AND spol.lot_id=%d
                """ %self.lot_id)
            sp_purchase = self._cr.fetchall()
            self._cr.execute(
                """
                   SELECT sp.id FROM stock_move_lots sml
                   LEFT JOIN stock_move sm on sml.move_id=sm.id
                   LEFT JOIN stock_picking sp ON sp.id=sm.picking_id WHERE sml.lot_id=%d
                """ %self.lot_id)
            # p_move_id = self.env['stock.move.lots'].search([('lot_id','=',self.lot_id.id)]).move_id
            # p_picking_id = self.env['stock.move'].search([('id','=',p_move_id.id)]).picking_id
            # print p_picking_id
            sp_mrp = self._cr.fetchall()
            # print sp_mrp
            dom=(0,)
            mrp_dom=0
            # print sp_purchase
            if any(sp_purchase):
                # print 222
                dom = sp_purchase
            elif any(sp_mrp):
                # print 333
                move_lots=self.env['stock.move.lots'].search([('lot_id','=',self.lot_id.id)])
                # moves=self.env['stock.move'].search[('lot_id','=',self.lot_id)]
                for rcd in move_lots:
                    # i=111111
                    if any(rcd.move_id.production_id):
                        # print i
                        self.mrp_id = rcd.move_id.production_id
                        # i=i+111111
                        mrp_dom=self.mrp_id.id
                # dom = sp_mrp
            else:
                dom = (0,)
            return {
                'domain': {'picking_id': [('id', 'in', dom)],'mrp_id': [('id', '=', mrp_dom)]}
            }

    # @api.multi
    # def name_get(self):
    #     res = []
    #     for prl in self:
    #         print prl
    #         res.append((prl.id, prl.name))
    #     return res



class QualityOrderLine(models.Model):
    _name = "quality.order.line"
    _description = 'Quality Order Line'
    _order = "qo_id,sequence"

    qo_id = fields.Many2one('quality.order', u'质检单')
    qc_id = fields.Many2one('quality.check', u'质检方案', related='qo_id.qc_id')
    qp_id = fields.Many2one('qc.para', '参数名称', required=True)
    qm_id = fields.Many2one('qc.mid', u'方案明细', required=True)

    @api.onchange('para')
    def _onchange_para(self):
        if self.qp_id:
            self._cr.execute(
                """SELECT up_value,low_value,standard_value FROM qc_para WHERE para =\'%s\' """ %
                self.qp_id.name_get()[0][1])
            rlist = self._cr.fetchall()
            # self.standard_value = rlist[0][0]
            self.up_value = rlist[0][0]
            self.low_value = rlist[0][1]
            self.standard_value = rlist[0][2]

    # standard_value = fields.Float(u'参数值', required=True)
    # para = fields.Char(u'参数名称')
    standard_value = fields.Char(u'实际值2')
    real_value = fields.Float(u'实际值', required=True)
    up_value = fields.Float(u'上限', related='qm_id.up_value',store=True)
    low_value = fields.Float(u'下限', related='qm_id.low_value',store=True)
    # order_name = name = fields.Char(string=u'质检单号', related='qo_id.name')
    order_produce_time = fields.Datetime(string=u'生产时间',related='qo_id.produce_time')
    order_qua_user = fields.Many2one('res.users', u'质检员', related='qo_id.qua_user')
    product_id = fields.Many2one('product.product', u'产品名称', related='qo_id.product_id',store=True)
    lot_id = fields.Many2one('stock.production.lot', u'批次号',related='qo_id.lot_id',store=True)
    sequence = fields.Integer()
